package com.njdj.gps.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.njdj.gps.common.constants.MonitorConstants;

/**
 * request interface and get response
 * @author leiyong created on 2009-06-12
 *
 */
public class DesireInterfaceUtil {
	
	protected static Log log = LogFactory.getLog(DesireInterfaceUtil.class);
	
	public static String getInterfaceResponse(String urlstr)
	{
		URL url=null;
		HttpURLConnection httpurl = null;
		BufferedReader reader=null;
		StringBuffer document = new StringBuffer();
		String timeout="";
		String result = MonitorConstants.SNIFFER_RESULT_FALSE;
	    boolean isSuccess = false;//判断是否成功
	    
		try {
			url = new URL(urlstr);
			if(timeout == null || timeout.trim().length() < 1)
			{
				timeout = MonitorConstants.HTTP_SNIFFER_TIMEOUT;
			}
			
			System.setProperty("sun.net.client.defaultConnectTimeout", timeout);//设置连接超时 
			System.setProperty("sun.net.client.defaultReadTimeout", timeout);//设置读取超时
		    httpurl=(HttpURLConnection)url.openConnection();//创建连接
		  
			if(httpurl.getResponseCode() == HttpURLConnection.HTTP_OK) 
			{	
				result = MonitorConstants.SNIFFER_RESULT_OK;
			}
			else 
			{
				log.info("###HttpURLConnection restart connection###");
				httpurl = (HttpURLConnection) url.openConnection();
				if(httpurl.getResponseCode() == HttpURLConnection.HTTP_OK)
				{
					result = MonitorConstants.SNIFFER_RESULT_OK;
				}
			}
		   
			
	        //获得响应内容
			if(result.equals(MonitorConstants.SNIFFER_RESULT_OK))
			{
			    reader = new BufferedReader(new InputStreamReader(httpurl.getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) 
				{
					document.append(line);
				} 
				isSuccess =true;
				log.info("###get response content:"+document.toString());
			}else
			{
				log.error("###no response content###");
			}
		        
		}catch (MalformedURLException e) {
				// TODO Auto-generated catch block
			log.error("###url exception:"+e.toString());
			} 
	      catch (IOException e) {
	    	log.error("###IO exception1:"+e.toString());  	       
	      }
	      catch (Exception e) {
	    	log.error("###IO exception2:"+e.toString());  
	      }
		finally
		{
			try {
				log.info("###close reader start###");
				if(reader!=null)
				{
					reader.close();
				}
				log.info("###close reader end###");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("###close reader exception:"+e.toString());
			}

		}
		return document.toString();
	}

}
